package com.correction.service;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.correction.classes.Examen;
import com.correction.classes.Exercice;
import com.correction.classes.Utilisateur.Niveau;
import com.correction.utils.HibernateUtil;

public class ExerciceDAO {
	public static Exercice saveExercice(Exercice exo) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.saveOrUpdate(exo);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return exo;

	}

	public static List<Exercice> getAll() {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		List<Exercice> exos = null;
		try {
			transaction = session.beginTransaction();
			exos = session.createCriteria(Exercice.class).list();
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return exos;
	}
	
	public static List<Exercice> getExerciceByNiveau(Niveau niveau) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<Exercice> exercice = null;
		String hql = "FROM Exercice e where (e.niveau='" + niveau.name() + "')";
		exercice = (List<Exercice>) session.createQuery(hql).list();
		session.close();
		
		return exercice;
	}
	
	public static List<Exercice> getExerciceByNiveauAndStatut(Niveau niveau,int statut) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<Exercice> exercice = null;
		String hql = "FROM Examen e where (e.niveau='" + niveau.name() + "') and (e.statut='" + statut + "')";
		exercice = (List<Exercice>) session.createQuery(hql).list();
		session.close();
		
		return exercice;
	}

	public static Exercice getExercice(int id) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Exercice exo = null;
		String hql = "FROM Exercice e where (e.id='" + id + "')";
		exo = (Exercice) session.createQuery(hql).uniqueResult();
		session.close();

		return exo;
	}

	public static void deleteExercice(Exercice exercice) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		session.delete(exercice);
		session.getTransaction().commit();
		session.close();
		
	}
}